import {defineStore} from "pinia";
import {getOrderByUserId} from "@/router/api";

interface OrderData {
    id: number
    no: string
    total: number,
    pay_type:number
}

export const useOrderStore = defineStore('order', {
    state: () => ({
        currentOrder: null as OrderData | null,
        orderHistory: [] as OrderData[]
    }),
    getters: {
        // 新增安全访问方法
        safeCurrentOrder: (state) => {
            if (!state.currentOrder) {
                throw new Error('当前订单未初始化')
            }
            return state.currentOrder
        }
    },
    actions: {
        setCurrentOrder(order: OrderData) {
            this.currentOrder = order
            this.orderHistory.unshift(order) // 添加到历史记录
        },

        // 从API加载历史订单
        async loadOrderHistory(userId: number) {
            const res = await getOrderByUserId(userId)
            this.orderHistory = res.data
        }
    }
})